from django.shortcuts import render

# Create your views here.
from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.
from django.http import HttpResponse
import json
import requests
import time
from bs4 import BeautifulSoup
import time
import re
import json
from bs4 import BeautifulSoup
import urllib


def buildingParameters(data):
    data["log"].append("###")

    typeCorr = {
        "TI": "1",
        "AU": "2",
        "KY": "3"
    }

    logCorr = {
        "and": "1",
        "or": "2",
        "not": "3",
        "###": "1"
    }

    # print(data)
    # exit()

    tempStr = []
    for i in range(len(data["values"])):
        try:
            strr = "{}^1^{}^{}".format(typeCorr[data["type"][i]],logCorr[data["log"][i]],urllib.parse.quote(data["values"][i]))
            tempStr.append(strr)
        except:
            raise

    if len(tempStr) == 0:
        return -1

    strr = ''
    for value in tempStr:
        strr += value + "|"

    return strr.strip().strip("|").strip()

#返回结果格式
def resultData():
    data = {
        "websiteType" : 0,
        "titleName":"",
        "titleHref": "",
        "source":"",
        "label":"",
        "volume":"",
        "summary":"",
        "detailId":'',
        "publishTime" :"",
        "category" : "",
        "quote" :"",
        "abstract": "",
        "doi": "",
        "downLoad": "",
        "keyword": [],
        "author": [],

    }
    return data

def formData(response):
    soup = BeautifulSoup(response.text, "html5lib")

    # allNum = soup.select("#totalcount")[0].text.strip()


    lis = soup.select(".listOne")


    allData = []

    for li in lis:
        tempData = resultData()

        try:
            tempData["titleName"] = li.select("a")[0].text.strip()
        except:
            pass
        try:
            tempData["titleHref"] = "http://qikan.chaoxing.com" + li.select("a")[0]["href"]
        except:
            pass

        try:
            tempData["publishTime"] = titles[i].select("span")[0].text.strip()
        except:
            pass

        try:
            tempData["abstract"] = li.select(".detal")[0].text.strip()
        except:
            pass
        allData.append(tempData)

    return allData

def getData(keyword):

    headers = {
        'Connection': 'keep-alive',
        'Cache-Control': 'max-age=0',
        'Upgrade-Insecure-Requests': '1',
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.96 Safari/537.36',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
        'Accept-Encoding': 'gzip, deflate',
        'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
    }

    params = (
        ('sw', keyword),
        ('topsearch', '0'),
        ('size', '50'),
    )

    response = requests.get('http://qikan.chaoxing.com/searchjour', headers=headers, params=params)

    allData = formData(response)

    return allData
    # NB. Original query string below. It seems impossible to parse and
    # reproduce query strings 100% accurately so the one below is given
    # in case the reproduced version is not "correct".
    # response = requests.get('http://qikan.chaoxing.com/searchjour?adv=T%3D%E7%BB%86%E8%83%9E+AND+A%3Dz&aorp=p&size=50', headers=headers, cookies=cookies)


def index(request):

    data = json.loads(request.POST.get('data', '1'))

    allData= getData(data["values"][0])

    return HttpResponse(json.dumps({
        "collection": allData,
        "allNum": 0
    }), content_type="application/json")